#include "./src/shared.h"

// Index into the light textures
uniform float lightScale;
uniform float indirectScale;
uniform float indirectLookupScale;
uniform int useNegativeIndirectLight;

// Deferred shader textures
samplerRect dsEC;
samplerRect dsNorm;
samplerRect dsColor;
samplerRect indirectTex;
samplerRect indirectNegTex;

void main (void)
{
	// TODO add specular
	vec4 final;
	vec4 indirect;
	vec4 indirectNeg;

	vec3 n = normalize(textureRect(dsNorm, gl_FragCoord));
	vec4 positionShadow = textureRect(dsEC, gl_FragCoord);
	vec3 position = vec3(positionShadow);
	vec4 diffuse = textureRect(dsColor, gl_FragCoord);
    
	vec3 lightPosition = gl_LightSource[0].position;
	vec4 lightDiffuse = gl_LightSource[0].diffuse;
	vec3 toLight = lightPosition - position;
	float dis = length(toLight);
	toLight = normalize(toLight);
	float spotDot = dot(-toLight, normalize(gl_LightSource[0].spotDirection));
	float att;
	float spotAtt;
	
	float nDotL= max(0.0, dot(n,toLight));

	if (spotDot < gl_LightSource[0].spotCosCutoff) {
		spotAtt = 0.0;
	} else {
		spotAtt = pow(spotDot, gl_LightSource[0].spotExponent);
	}
	att = spotAtt * 1/(gl_LightSource[0].constantAttenuation + 
			gl_LightSource[0].linearAttenuation*dis + 
			gl_LightSource[0].quadraticAttenuation*dis*dis);

	final += lightDiffuse * diffuse * nDotL * att;	
	
	indirect = textureRect(indirectTex, gl_FragCoord);
	indirectNeg = useNegativeIndirectLight ? textureRect(indirectNegTex, gl_FragCoord) : 0.0;
	//if (indirect == vec4(0.0, 0.0, 0.0, 1.0)) {
    //		indirect = textureRect(indirectLo, gl_FragCoord/LO_RES_REDUCTION);
	//}
	gl_FragColor = final * lightScale * positionShadow.w + (indirect-indirectNeg) * indirectScale;
}

